//
//  YDANewsController.m
//  siyanone
//
//  Created by LK-IOS on 2018/3/21.
//  Copyright © 2018年 LK-News. All rights reserved.
//

#import "YDANewsController.h"
#import "YDAWeekNewModel.h"
#import "YDAWeekNewCell.h"
#import "YDDayNewsController.h"

#pragma 跳转新闻详情
#import "YDSingleStockNewsModel.h"
#import "YDVerticalStockNewDetailController.h"

@interface YDANewsController ()<UITableViewDelegate , UITableViewDataSource>

@property (nonatomic , weak) SYNoNetView *noNetView;
@property (nonatomic , weak) SYNoDataView *noDataView;
@property (nonatomic, weak)UITableView *tableView;
@property (nonatomic , strong) NSMutableArray *modelArray;
@property (nonatomic , assign) NSInteger currentPage;

@end

@implementation YDANewsController

-(NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    self.title = @"亿点远期要闻";
    
    [self setUpNavButton];
    
    
    [self tableView];
    
    
    [self setUpDataManger];
    
    [self loadData];
    
}

- (void)removeNoNetView
{
    if (_noNetView != nil) {
        [_noNetView removeFromSuperview];
        _noNetView = nil;
    }
}

- (void)removeNodataView
{
    if (_noDataView != nil) {
        [_noDataView removeFromSuperview];
        _noDataView = nil;
    }
}

#pragma 添加导航栏按钮
-(void)setUpNavButton
{
    UIBarButtonItem *rightItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"zdjianxun"] hightImage:[UIImage imageNamed:@"zdjianxun"] addTarget:self action:@selector(rightItemButtonClick:)];
    self.navigationItem.rightBarButtonItem = rightItemBtn;
}
//7*24
-(void)rightItemButtonClick:(UIButton *)button
{
    YDDayNewsController *vc = [[YDDayNewsController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)setUpDataManger
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    
    header.lastUpdatedTimeLabel.hidden = NO;//是否隐藏最后一次刷新时间
    header.stateLabel.hidden = NO;//是否隐藏刷新状
    self.tableView.mj_header = header;
    [header beginRefreshing];//马上进入刷新
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}

- (void)loadData
{
    self.currentPage = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.currentPage) forKey:@"page"];
    [dict setObject:@(10) forKey:@"pageSize"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:WeekNews WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [self.tableView.mj_header endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.modelArray removeAllObjects];
            self.modelArray = [YDAWeekNewModel mj_objectArrayWithKeyValuesArray:resultDict[@"data"]];
            
            if (self.modelArray.count < 10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
            }
            
            [self.tableView reloadData];
            
            [self removeNoNetView];
            //没有数据加载nodataView
            if (!self.modelArray.count) {
                
                [self noDataView];
            }
        
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"msg"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        
        if (!self.modelArray.count) {
            //没网如果内存没有数据源加载noNetVIew
            [self removeNodataView];
            [self noNetView];
        }
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
    }];
    
}

-(void)loadMoreData
{
    self.currentPage++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.currentPage) forKey:@"page"];
    [dict setObject:@(10) forKey:@"pageSize"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:WeekNews WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [self.tableView.mj_footer endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            
            NSArray *newsArr =  [YDAWeekNewModel mj_objectArrayWithKeyValuesArray:resultDict[@"data"]];
            
            
            [self.modelArray addObjectsFromArray:newsArr];
            
            
            if (newsArr.count < 10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            
            [self.tableView reloadData];
            
            
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"msg"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
    }];
    
}


-(UITableView *)tableView
{
    if (_tableView == nil) {
        CGFloat safeTopH = isPhoneX ? 84 : 64;
        CGFloat safeBottomH = isPhoneX ? 83 : 49;
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, LKScreenH - safeTopH - safeBottomH) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor colorWithHexString:mainGray];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.showsVerticalScrollIndicator = NO;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDAWeekNewModel *model = self.modelArray[indexPath.row];
    return model.cellH;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDAWeekNewCell *cell = [YDAWeekNewCell cellWithTbaleview:tableView];
    cell.model = [self.modelArray objectAtIndex:indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
#pragma 跳转到新闻详情
    if (!self.modelArray.count)return;
    //数据
    YDAWeekNewModel *newModel = self.modelArray[indexPath.row];
    YDSingleStockNewsModel *singleStockNewsModel = [[YDSingleStockNewsModel alloc] init];
    singleStockNewsModel.createDate = newModel.createTime;
    singleStockNewsModel.title = newModel.title;
    singleStockNewsModel.Id = newModel.Id;
    
    //跳转
    YDVerticalStockNewDetailController *vc = [[YDVerticalStockNewDetailController alloc] init];
    vc.style = NewDetailWeeknews;
    vc.model = singleStockNewsModel;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(SYNoDataView *)noDataView
{
    if (_noDataView == nil) {
        CGFloat dataW = rate375(240);
        CGFloat dataX = (LKScreenW - dataW) * 0.5;
        CGFloat dataH = isPhoneX ? rateX812(196) : rate750(196);
        CGFloat dataY = isPhoneX ? rateX812(132) : rate750(132);
        CGRect frame = CGRectMake(dataX, dataY, dataW, dataH);
        SYNoDataView *noDataView = [SYNoDataView positionNoDataViewInitWithFrame:frame ImageString:@"wuneirong" buttonTitle:@"" IsCanSeeBuyButton:NO];
        [self.tableView addSubview:noDataView];
        _noDataView = noDataView;
    }
    return _noDataView;
}

-(SYNoNetView *)noNetView
{
    if (_noNetView == nil) {
        SYNoNetView *noNetView = [[SYNoNetView alloc] init];
        [self.tableView addSubview:noNetView];
        
        [noNetView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
        }];
        LK(weself)
        [noNetView setClickBlock:^(BOOL isClick) {
#warning 无网络刷新
//            [weself.tableView.mj_header beginRefreshing];
            
            
        }];
        _noNetView = noNetView;
    }
    return _noNetView;
}

@end
